﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Home.Haushalt.Lib;
using Home.Haushalt.Lib.Element;
using Infragistics.Win;
using Infragistics.Win.SupportDialogs.FilterUIProvider;
using Infragistics.Win.UltraWinGrid;

namespace Home.Haushalt.Gui
{
    /// <summary>
    /// 
    /// </summary>
    public class HGrid : UltraGrid
    {
        #region EVENTS

        /// <summary></summary>
        public event EventHandler<HEventArgs> OnLayoutChanged;

        /// <summary></summary>
        public event EventHandler<HEventArgs> OnElementDeleting;

        /// <summary></summary>
        public event EventHandler<HEventArgs> OnRefresh;

        /// <summary></summary>
        public event EventHandler<HEventArgs> OnSelect;

        /// <summary>
        /// 
        /// </summary>
        public void OnGridRefresh()
        {
            if (OnRefresh != null)
                OnRefresh(this, new HEventArgs(""));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        protected void OnElementDeletingApply(HEventArgs args)
        {
            if (OnElementDeleting != null)
                OnElementDeleting(this, args);
        }

        /// <summary></summary>
        public event EventHandler<HEventArgs> OnElementDeleted;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        protected void OnElementDeletedApply(HEventArgs args)
        {
            if (OnElementDeleted != null)
                OnElementDeleted(this, args);
        }

        /// <summary></summary>
        public event EventHandler<HEventArgs> OnElementChanged;


        /// <summary></summary>
        public event EventHandler<HEventArgs> OnStatusMessage;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        protected void OnStatusMessageApply(HEventArgs args)
        {
            if (OnStatusMessage != null)
                OnStatusMessage(this, args);
        }


        #endregion EVENTS

        /// <summary></summary>
        public ElementBase ParentElement;

        /// <summary></summary>
        public object _clickedObject;

        /// <summary></summary>
        protected Type _elementType;

        /// <summary></summary>
        public Type ElementType { get { return _elementType; } set { _elementType = value; } }

        /// <summary></summary>
        protected MemoryStream _defaultLayout = new MemoryStream();

        /// <summary></summary>
        private bool _allowColumnManagement = true;
        /// <summary></summary>
        public bool AllowColumnManagement
        {
            get { return _allowColumnManagement; }
            set { _allowColumnManagement = value; }
        }

        /// <summary></summary>
        private bool _allowLayoutManagement = true;
        /// <summary></summary>
        public bool AllowLayoutManagement
        {
            get { return _allowLayoutManagement; }
            set { _allowLayoutManagement = value; }
        }

        /// <summary></summary>
        private DefaultColumnSets _defaultColumnSet = DefaultColumnSets.GridDefault;

        /// <summary></summary>
        private string _currentLayoutName = "";

        /// <summary></summary>
        public string CurrentLayoutName
        {
            get { return _currentLayoutName; }
            set
            {
                _currentLayoutName = value;

                CurrentLayout = GridLayout.FindLayout(_currentLayoutName, _elementType);

                if (OnLayoutChanged != null)
                    OnLayoutChanged(this, new HEventArgs("Layout geändert", _currentLayoutName));
            }
        }

        /// <summary></summary>
        public GridLayout CurrentLayout { get; private set; }

        #region ROWS COLLECTIONS

        /// <summary></summary>
        public List<UltraGridRow> VisibleRows
        {
            get
            {
                List<UltraGridRow> rows = new List<UltraGridRow>();

                UIElement element = this.DisplayLayout.UIElement;
                if (element != null)
                {
                    element = element.GetDescendant(typeof(DataAreaUIElement));
                    if (element != null)
                    {
                        element = element.GetDescendant(typeof(RowColRegionIntersectionUIElement));
                        if (element != null)
                        {
                            foreach (UIElement childElement in element.ChildElements)
                            {
                                if (childElement is RowUIElement)
                                {
                                    UltraGridRow row = childElement.GetContext() as UltraGridRow;
                                    if (row != null)
                                        rows.Add(row);
                                }
                            }
                        }
                    }
                }

                return rows;
            }
        }

        /// <summary></summary>
        public List<UltraGridRow> VisibleNewRows
        {
            get
            {
                List<UltraGridRow> rows = new List<UltraGridRow>();

                UIElement element = this.DisplayLayout.UIElement;
                if (element != null)
                {
                    element = element.GetDescendant(typeof(DataAreaUIElement));
                    if (element != null)
                    {
                        element = element.GetDescendant(typeof(RowColRegionIntersectionUIElement));
                        if (element != null)
                        {
                            foreach (UIElement childElement in element.ChildElements)
                            {
                                if (childElement is RowUIElement)
                                {
                                    UltraGridRow row = childElement.GetContext() as UltraGridRow;
                                    if (row != null && row.Band.Columns.Exists(ElementBase.ELEMENTPROPERTY_ID) && row.Cells[ElementBase.ELEMENTPROPERTY_ID].Value.Equals(-1))
                                        rows.Add(row);
                                }
                            }
                        }
                    }
                }

                return rows;
            }
        }

        /// <summary></summary>
        public List<UltraGridRow> SelectedRows
        {
            get
            {
                List<UltraGridRow> rows = new List<UltraGridRow>();

                foreach (UltraGridRow row in this.Selected.Rows)
                {
                    rows.Add(row);
                }

                return rows;
            }
        }

        #endregion ROWS COLLECTIONS

        /// <summary>
        /// 
        /// </summary>
        public HGrid()
        {
            //Contextmenu
            this.ContextMenuStrip = new ContextMenuStrip();
            //this.ContextMenuStrip.Opened += new EventHandler(ContextMenuStripOpened);
            this.ContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(ContextMenuStripOpened);

            //Data editing
            base.AfterExitEditMode += new EventHandler(HaushaltGrid_AfterExitEditMode);
            base.CellDataError += new CellDataErrorEventHandler(HaushaltGrid_CellDataError);
            base.KeyUp += new KeyEventHandler(HaushaltGrid_KeyUp);
            base.AfterCellUpdate += new CellEventHandler(HaushaltGrid_AfterCellUpdate);
            base.AfterCellListCloseUp += new CellEventHandler(HGrid_AfterCellListCloseUp);
            base.AfterRowInsert += new RowEventHandler(HGrid_AfterRowInsert);
            this.MouseDown += new MouseEventHandler(HGrid_MouseDown);
            this.MouseUp += new MouseEventHandler(HGrid_MouseUp);
            base.BeforeRowFilterDropDownPopulate += new BeforeRowFilterDropDownPopulateEventHandler(HaushaltGrid_BeforeRowFilterDropDownPopulate);
            base.AfterRowActivate += new EventHandler(HGrid_AfterRowActivate);
            base.AfterSelectChange += new AfterSelectChangeEventHandler(HGrid_AfterSelectChange);
            base.KeyDown += new KeyEventHandler(HGrid_KeyDown);

            //ContextMenu initialisieren, damit event "Opened" funktioniert (sonst ist menu leer und wird nicht geöffnet)
            this.ContextMenuStrip.Items.Add("-");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HGrid_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control)
            {
                switch (e.KeyCode)
                {
                    case Keys.A:
                        SelectAllGridRows();
                        break;

                    case Keys.C:
                        CopyOverviewToClipboard(SelectedRows);
                        break;
                }

            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void SelectAllGridRows()
        {
            base.Rows.Cast<UltraGridRow>().Where(row => !row.VisibleIndex.Equals(-1)).ToList().ForEach(row => row.Selected = true);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HGrid_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)
        {
            if (OnSelect != null)
            {
                OnSelect(this, new HEventArgs(""));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HGrid_AfterRowActivate(object sender, EventArgs e)
        {
            this.DisplayLayout.Override.ActiveRowAppearance.ForeColor = ActiveRow.CellAppearance.ForeColor;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HGrid_AfterRowInsert(object sender, RowEventArgs e)
        {
            e.Row.RefreshSortPosition();
        }

        /// <summary>
        /// 
        /// </summary>
        protected override void OnCreateControl()
        {
            base.OnCreateControl();

            this.DisplayLayout.GroupByBox.Hidden = true;
            this.DisplayLayout.CaptionVisible = DefaultableBoolean.False;

            //Appearances
            this.DisplayLayout.Override.CellAppearance.BorderColor = Color.LightBlue;
            this.DisplayLayout.Override.RowAppearance.BorderColor = Color.LightBlue;
            this.DisplayLayout.Override.HeaderAppearance.BorderColor = Color.LightBlue;
            this.DisplayLayout.Override.HeaderAppearance.BackColor = Color.White;
            this.DisplayLayout.Override.HeaderAppearance.BackColor2 = Color.LightBlue;

            this.DisplayLayout.Override.CellAppearance.TextVAlign = VAlign.Middle;
            this.DisplayLayout.Override.ActiveRowAppearance.BackColor = Color.FromArgb(193, 237, 255);
        }

        #region EXPERT ROW FILTER

        /// <summary></summary>
        private const string FILTER_GREATERTHANOREQUALTO = "GreaterThanOrEqualTo";
        /// <summary></summary>
        private const string FILTER_LESSTHANOREQUALTO = "LessThanOrEqualTo";
        /// <summary></summary>
        private const string FILTER_OLD = "Old";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentFormComponents"></param>
        public void AllowExpertFilter(System.ComponentModel.IContainer parentFormComponents)
        {
            UltraGridFilterUIProvider ultraGridFilterUIProvider1 = new UltraGridFilterUIProvider(parentFormComponents);
            ultraGridFilterUIProvider1.ViewStyle = FilterUIProviderViewStyle.Office2007;
            ultraGridFilterUIProvider1.BeforeMenuPopulate += new BeforeMenuPopulateEventHandler(ultraGridFilterUIProvider1_BeforeMenuPopulate);
            ultraGridFilterUIProvider1.ButtonToolClick += new ButtonToolClickEventHandler(ultraGridFilterUIProvider1_ButtonToolClick);
            this.DisplayLayout.Override.FilterUIProvider = ultraGridFilterUIProvider1;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ultraGridFilterUIProvider1_ButtonToolClick(object sender, ButtonToolClickEventArgs e)
        {
            switch (e.Tool.Id)
            {
                case FILTER_GREATERTHANOREQUALTO:

                    e.ColumnFilter.LogicalOperator = FilterLogicalOperator.Or;

                    using (FilterCondition filter = new FilterCondition(FilterComparisionOperator.GreaterThanOrEqualTo, SpecialFilterOperands.Today))
                    {
                        e.ColumnFilter.FilterConditions.Add(filter);
                    }
                    using (FilterCondition filter = new FilterCondition(FilterComparisionOperator.Equals, null))
                    {
                        e.ColumnFilter.FilterConditions.Add(filter);
                    }

                    break;

                case FILTER_LESSTHANOREQUALTO:
                    using (FilterCondition filter = new FilterCondition(FilterComparisionOperator.LessThanOrEqualTo, SpecialFilterOperands.Today))
                    {
                        e.ColumnFilter.FilterConditions.Add(filter);
                    }
                    break;
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ultraGridFilterUIProvider1_BeforeMenuPopulate(object sender, BeforeMenuPopulateEventArgs e)
        {
            if (e.ColumnFilter.Column.DataType == typeof(DateTime))
            {

                FilterButtonTool activeTool = new FilterButtonTool(FILTER_GREATERTHANOREQUALTO, "Größer als heute (heute inkl.)");
                e.MenuItems.Add(activeTool);

                FilterButtonTool futureTool = new FilterButtonTool(FILTER_LESSTHANOREQUALTO, "Kleiner als heute (heute inkl.)");
                e.MenuItems.Add(futureTool);
            }
            //e.Handled = false;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HaushaltGrid_BeforeRowFilterDropDownPopulate(object sender, BeforeRowFilterDropDownPopulateEventArgs e)
        {
            if (base.ActiveRow != null && base.ActiveRow.Cells != null && base.ActiveRow.Cells.IndexOf(e.Column.Key) > -1)
            {
                string suchwort = base.ActiveRow.Cells[e.Column].Value.ToString();
                e.ValueList.ValueListItems.Add(suchwort, "(Akt.Wert)");
            }
        }

        #endregion EXPERT ROW FILTER

        #region DATA BINDING

        /// <summary>
        /// 
        /// </summary>
        /// <param name="elementType"></param>
        /// <param name="columnSetName"></param>
        public void DataBind(Type elementType, DefaultColumnSets columnSetName)
        {
            DataBind(ElementBase.Instantiate(elementType), columnSetName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="elementObj"></param>
        /// <param name="columnSetName"></param>
        public void DataBind(ElementBase elementObj, DefaultColumnSets columnSetName)
        {
            _elementType = elementObj.GetType();
            _defaultColumnSet = columnSetName;

            this.DisplayLayout.Override.AllowRowFiltering = _allowLayoutManagement ? DefaultableBoolean.True : DefaultableBoolean.False;
            if (!_allowLayoutManagement)
            {
                this.DisplayLayout.Override.HeaderClickAction = HeaderClickAction.Select;
            }

            //Create default layout
            LayoutController.InitColumnLayout(_elementType, elementObj.ElementTable, columnSetName, this.DisplayLayout);

            //DataBind
            this.DataSource = elementObj.ElementTable;

            this.DisplayLayout.Save(_defaultLayout);

            CurrentLayoutName = columnSetName.ToString();

            this.DisplayLayout.Override.RowSelectors = DefaultableBoolean.False;

            this.ActiveRow = null;
        }

        /// <summary>
        /// 
        /// </summary>
        public void CalculateUnboundFields()
        {
            if (!this.Rows.Count.Equals(0))
            {
                ElementBase elementObj = ElementBase.Instantiate(this.Rows[0].ToDataRow());

                elementObj.PreCalculateUnboundFields();

                foreach (UltraGridRow row in this.Rows)
                {
                    CalculateUnboundField(row);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        private static ElementBase CalculateUnboundField(UltraGridRow row)
        {
            ElementBase elementObj = ElementBase.Instantiate(row.ToDataRow());
            ElementBase result = null;

            //Kalkulierung der ungebundenden Cells
            foreach (KeyValuePair<string, object> columnPair in elementObj.CalculateUnboundFields())
            {
                if (row.Cells.Exists(columnPair.Key))
                {
                    row.Cells[columnPair.Key].Value = columnPair.Value;
                    result = elementObj;
                }
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        public void InitializeRowsAppearances()
        {
            foreach (UltraGridRow row in this.Rows)
            {
                ElementBase elementObj = ElementBase.Instantiate(row.ToDataRow());

                //Row Appearances
                row.CellAppearance.ForeColor = elementObj.GetRowForeColor();
                row.CellAppearance.BackColor = elementObj.GetRowBackgroundColor();
            }
        }

        #endregion DATA BINDING

        #region DATA EDITING

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private FrmProperty EditElementProperty(List<DataRow> rows)
        {
            FrmProperty frmProperty = WindowController.EditElementProperty(this, rows);

            return frmProperty;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public FrmProperty EditElementProperty()
        {
            return EditElementProperty(Selected.Rows.Cast<UltraGridRow>().Select(item => item.ToDataRow()).ToList());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public FrmProperty EditElementProperty(DataRow row)
        {
            return EditElementProperty(new DataRow[] { row }.ToList());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HaushaltGrid_CellDataError(object sender, CellDataErrorEventArgs e)
        {
            MessageBox.Show("Datenformat ist falsch");
            e.StayInEditMode = true;
            e.RaiseErrorEvent = false;

            this.ActiveCell.SelectAll();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HaushaltGrid_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode.Equals(Keys.Enter))
            {
                if (this.ActiveCell != null && this.ActiveCell.IsInEditMode)
                {
                    this.PerformAction(UltraGridAction.ExitEditMode);
                }
            }
            else if (e.Control && e.KeyCode.Equals(Keys.D))
            {
                if (this.SelectedRows != null)
                {
                    foreach (UltraGridRow row in this.SelectedRows)
                    {
                        foreach (UltraGridCell cell in row.Cells)
                        {
                            if (cell.Value is DateTime && !cell.Hidden)
                            {
                                cell.Value = DateTime.Now;
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HGrid_MouseUp(object sender, MouseEventArgs e)
        {
            if (this.ActiveCell != null && this.ActiveCell.Column.DataType != typeof(DateTime) && this.ActiveCell.IsInEditMode)
            {
                this.PerformAction(UltraGridAction.ExitEditMode);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HGrid_AfterCellListCloseUp(object sender, CellEventArgs e)
        {
            this.PerformAction(UltraGridAction.ExitEditMode);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HaushaltGrid_AfterExitEditMode(object sender, EventArgs e)
        {
            //this.UpdateData();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HaushaltGrid_AfterCellUpdate(object sender, CellEventArgs e)
        {
            if (this.ActiveRow != null && e.Cell.Row.ToDataRow().Table.Columns.Contains(e.Cell.Column.Key))
            {
                CellUpdate(e.Cell.Row.ToDataRow());
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="rows"></param>
        internal void CellUpdate(params DataRow[] rows)
        {
            foreach (DataRow row in rows)
            {
                if (row[ElementBase.ELEMENTPROPERTY_ID].ToInt() < 0)
                {
                    row[ElementBase.ELEMENTPROPERTY_ID] = ElementBase.GetNextId(_elementType);
                    //return;
                }

                //ElementBase.Instantiate(e.Cell.Row.ToDataRow()).SaveToChangeBackup();
                row.AcceptChanges();
            }

            Application.DoEvents();

            if (OnElementChanged != null)
                OnElementChanged(this, new HEventArgs("Wert ist verändert"));

            ElementBase.Instantiate(rows[0]).MarkAsChanged();

            WindowController.RefreshGrids(ElementType);
            WindowController.RefreshMonthbalanceGrids();
        }

        #endregion DATA EDITING

        #region CONTEXTMENU

        /// <summary></summary>
        public ToolStripMenuItem ContextMenuNewElementItem;
        /// <summary></summary>
        public ToolStripMenuItem ContextMenuCopyElementItem;
        /// <summary></summary>
        public ToolStripMenuItem ContextMenuDeleteElementItem;
        /// <summary></summary>
        public ToolStripMenuItem ContextMenuCopyOverviewItem;
        /// <summary></summary>
        public ToolStripSeparator ContextMenuPropertySeparatorItem;
        /// <summary></summary>
        public ToolStripSeparator ContextMenuPropertySeparator2Item;
        /// <summary></summary>
        public ToolStripMenuItem ContextMenuPropertyElementItem;
        /// <summary></summary>
        public ToolStripMenuItem ContextMenuSummaryElementItem;
        /// <summary></summary>
        public ToolStripMenuItem ContextMenuParentPostenElementItem;
        /// <summary></summary>
        public ToolStripMenuItem ContextMenuParentOpponentElementItem;

        /// <summary></summary>
        private bool _gridEditMode = false;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ContextMenuStripOpened(object sender, EventArgs e)
        {
            this.ContextMenuStrip.Items.Clear();

            if (_clickedObject is UltraGridColumn)
            {
                if (_allowColumnManagement)
                {
                    this.ContextMenuStrip.Items.Add(LO.GridContextMenu("GridHeader.ManageColumns"), null, cmnuManageColumn_Click);

                    ToolStripMenuItem ContextMenuGroupByBoxElementItem = new ToolStripMenuItem(LO.GridContextMenu("GridHeader.ManageGroupByBox"), null, cmnuGroupBoxShow_Click);
                    ContextMenuGroupByBoxElementItem.Checked = !this.DisplayLayout.GroupByBox.Hidden;
                    this.ContextMenuStrip.Items.Add(ContextMenuGroupByBoxElementItem);

                    ContextMenuSummaryElementItem = new ToolStripMenuItem(LO.GridContextMenu("GridHeader.ShowSummary"), null, cmnuShowSummary_Click);
                    this.ContextMenuStrip.Items.Add(ContextMenuSummaryElementItem);
                    ContextMenuSummaryElementItem.Checked = (this.DisplayLayout.Override.AllowRowSummaries.Equals(AllowRowSummaries.True));


                    ToolStripMenuItem ContextMenuGridEditableItem = new ToolStripMenuItem(LO.GridContextMenu("GridHeader.GridEditable"), null, cmnuGridEditable_Click);
                    ContextMenuGridEditableItem.Checked = _gridEditMode;
                    this.ContextMenuStrip.Items.Add(ContextMenuGridEditableItem);
                    ContextMenuGridEditableItem.Enabled = !_elementType.Equals(typeof(Document));
                }
            }
            else
            {
                if (_clickedObject is UltraGridCell || _clickedObject is UltraGrid)
                {
                    bool singleSelection = Selected.Rows.Count.Equals(1);

                    string elementCaption = singleSelection ? LO.ElementList(_elementType) : LO.ElementName(_elementType);

                    //Neu
                    ContextMenuNewElementItem = new ToolStripMenuItem(LO.GridContextMenu("Element.Create", elementCaption), global:: Home.Haushalt.Lib.Properties.Resources.element_new, cmnuPropertyNew_Click);
                    this.ContextMenuStrip.Items.Add(ContextMenuNewElementItem);

                    //Kopieren
                    ContextMenuCopyElementItem = new ToolStripMenuItem(LO.GridContextMenu("Element.Copy", elementCaption), global:: Home.Haushalt.Lib.Properties.Resources.element_copy, cmnuPropertyCopy_Click);
                    ContextMenuCopyElementItem.Enabled = (Selected.Rows.Count > 0);
                    this.ContextMenuStrip.Items.Add(ContextMenuCopyElementItem);

                    //Löschen
                    ContextMenuDeleteElementItem = new ToolStripMenuItem(LO.GridContextMenu("Element.Delete", elementCaption), global:: Home.Haushalt.Lib.Properties.Resources.element_delete, cmnuPropertyDelete_Click);
                    ContextMenuDeleteElementItem.Enabled = (Selected.Rows.Count > 0);
                    this.ContextMenuStrip.Items.Add(ContextMenuDeleteElementItem);

                    ContextMenuPropertySeparatorItem = new ToolStripSeparator();
                    this.ContextMenuStrip.Items.Add(ContextMenuPropertySeparatorItem);

                    if (singleSelection)
                    {
                        #region PARENT ELEMENTE ÖFFNEN

                        //Parent Posten öffnen
                        int postenId = 0;
                        if (_elementType.Equals(typeof(Date))) postenId = Selected.Rows[0].Cells[Date.Fields.PostenId].Value.ToInt();
                        else if (_elementType.Equals(typeof(Document))) postenId = Selected.Rows[0].Cells[Document.Fields.PostenId].Value.ToInt();
                        else if (_elementType.Equals(typeof(Member))) postenId = Selected.Rows[0].Cells[Member.Fields.PostenId].Value.ToInt();

                        if (!postenId.Equals(0))
                        {
                            ContextMenuParentPostenElementItem = new ToolStripMenuItem(LO.GridContextMenu("Element.ParentPosten"), null, cmnuParentPostenPropertyEdit_Click);
                            ContextMenuParentPostenElementItem.Tag = postenId;
                            this.ContextMenuStrip.Items.Add(ContextMenuParentPostenElementItem);
                        }

                        //Parent Opponent öffnen
                        int opponentId = 0;
                        if (_elementType.Equals(typeof(Date))) opponentId = Selected.Rows[0].Cells[Date.Fields.OpponentId].Value.ToInt();
                        else if (_elementType.Equals(typeof(Document))) opponentId = Selected.Rows[0].Cells[Document.Fields.OpponentId].Value.ToInt();
                        else if (_elementType.Equals(typeof(Member))) opponentId = Selected.Rows[0].Cells[Member.Fields.OpponentId].Value.ToInt();
                        else if (_elementType.Equals(typeof(Posten))) opponentId = Selected.Rows[0].Cells[Posten.Fields.OpponentId].Value.ToInt();

                        if (!opponentId.Equals(0))
                        {
                            ContextMenuParentOpponentElementItem = new ToolStripMenuItem(LO.GridContextMenu("Element.ParentOpponent"), null, cmnuParentOpponentPropertyEdit_Click);
                            ContextMenuParentOpponentElementItem.Tag = opponentId;
                            this.ContextMenuStrip.Items.Add(ContextMenuParentOpponentElementItem);
                        }

                        if (!(postenId + opponentId).Equals(0))
                        {
                            ContextMenuPropertySeparator2Item = new ToolStripSeparator();
                            this.ContextMenuStrip.Items.Add(ContextMenuPropertySeparator2Item);
                        }

                        #endregion parent elemente öffnen
                    }

                    //Element-Eigenschaften öffnen
                    if (singleSelection)
                    {
                        ContextMenuPropertyElementItem = new ToolStripMenuItem(LO.GridContextMenu("Element.Property"), global:: Home.Haushalt.Lib.Properties.Resources.properties, cmnuPropertyEdit_Click);
                    }
                    else
                    {
                        // ContextMenuPropertyElementItem = new ToolStripMenuItem(LO.GridContextMenu(_elementType.Equals(typeof(Document)) ? "Element.PropertyMultiDocu" : "Element.PropertyMulti"), global:: Home.Haushalt.Lib.Properties.Resources.properties, cmnuPropertyEdit_Click);
                        ContextMenuPropertyElementItem = new ToolStripMenuItem(LO.GridContextMenu("Element.PropertyMulti"), global:: Home.Haushalt.Lib.Properties.Resources.properties, cmnuPropertyEdit_Click);
                    }
                    Type formType = Type.GetType("Home.Haushalt.Gui.FrmProperty" + _elementType.Name);
                    // ContextMenuPropertyElementItem.Enabled = (formType != null) && singleSelection || (!singleSelection && !_elementType.Equals(typeof(Document)));
                    ContextMenuPropertyElementItem.Enabled = (formType != null) && (Selected.Rows.Count > 0);
                    this.ContextMenuStrip.Items.Add(ContextMenuPropertyElementItem);

                    //Übersicht kopieren
                    ContextMenuCopyOverviewItem = new ToolStripMenuItem(LO.GridContextMenu("Element.CopyOverview", elementCaption), global:: Home.Haushalt.Lib.Properties.Resources.copy_to_clipboard, cmnuCopyOverviewToClipboard_Click);
                    ContextMenuCopyOverviewItem.Enabled = (Selected.Rows.Count > 0);
                    this.ContextMenuStrip.Items.Add(ContextMenuCopyOverviewItem);
                }

                //Layout Menus----------------------------------------------------
                if (_allowLayoutManagement)
                {
                    this.ContextMenuStrip.Items.Add(new ToolStripSeparator());

                    ToolStripMenuItem item = new ToolStripMenuItem(LO.GridContextMenu("Layout"));
                    this.ContextMenuStrip.Items.Add(item);

                    item.DropDownItems.Add(LO.GridContextMenu("Layout.Save", CurrentLayoutName), global:: Home.Haushalt.Lib.Properties.Resources.element_layout_user_save, SaveCurrentLayout_Click).Enabled = (CurrentLayoutName != _defaultColumnSet.ToString());
                    item.DropDownItems.Add(LO.GridContextMenu("Layout.Create"), global:: Home.Haushalt.Lib.Properties.Resources.element_layout_user_new, CreateLayout_Click);
                    item.DropDownItems.Add(LO.GridContextMenu("Layout.Delete", CurrentLayoutName), global:: Home.Haushalt.Lib.Properties.Resources.element_layout_user_delete, DeleteLayout_Click);
                    item.DropDownItems.Add(LO.GridContextMenu((_defaultColumnSet == DefaultColumnSets.GridDefault) ? "Layout.SaveAsDefault" : "Layout.SaveAsTabDefault"), global:: Home.Haushalt.Lib.Properties.Resources.element_layout_default_save, SaveDefaultLayout_Click);

                    item.DropDownItems.Add(new ToolStripSeparator());

                    //Layouts zu dem aktuellen Element
                    foreach (DataRow row in DAO.GetRows(GridLayout.ElementType, "{0} = '{1}' and {2} <> '{3}' and {2} <> '{4}'", GridLayout.Fields.Table, _elementType.Name, GridLayout.Fields.Name, DefaultColumnSets.GridDefault.ToString(), DefaultColumnSets.TabDefault.ToString()))
                    {
                        ToolStripMenuItem layoutItem = new ToolStripMenuItem(row[GridLayout.Fields.Name].ToString(), global:: Home.Haushalt.Lib.Properties.Resources.element_layout_user);
                        layoutItem.MouseUp += new MouseEventHandler(layoutItem_MouseUp);
                        layoutItem.Tag = row[GridLayout.Fields.Name];
                        item.DropDownItems.Add(layoutItem);
                    }

                    ToolStripMenuItem defaultLayoutItem = new ToolStripMenuItem(LO.GridContextMenu("Layout.DefaultName"), global:: Home.Haushalt.Lib.Properties.Resources.element_layout_default);
                    defaultLayoutItem.MouseUp += new MouseEventHandler(layoutItem_MouseUp);
                    defaultLayoutItem.Tag = _defaultColumnSet;
                    item.DropDownItems.Add(defaultLayoutItem);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuGridEditable_Click(object sender, EventArgs e)
        {
            _gridEditMode = !_gridEditMode;

            CellClickAction cellClickAction = _gridEditMode ? CellClickAction.EditAndSelectText : CellClickAction.RowSelect;
            Activation activation = _gridEditMode ? Activation.AllowEdit : Activation.ActivateOnly;

            foreach (UltraGridColumn col in this.DisplayLayout.Bands.Cast<UltraGridBand>().SelectMany(item => item.Columns.Cast<UltraGridColumn>()))
            {
                if (col.IsBound && col.ValueList == null)
                {
                    col.CellClickAction = cellClickAction;
                    col.CellActivation = activation;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuShowSummary_Click(object sender, EventArgs e)
        {
            SummarySettingsCollection ssc = this.DisplayLayout.Bands[0].Summaries;

            if (ssc.Count == 0)
            {
                this.DisplayLayout.Override.SummaryFooterCaptionVisible = Infragistics.Win.DefaultableBoolean.False;
                this.DisplayLayout.Override.SummaryValueAppearance.BackColor = Color.FromArgb(206, 231, 255);
                this.DisplayLayout.Override.SummaryFooterAppearance.BackColor = Color.FromArgb(206, 231, 255);

                this.DisplayLayout.Override.AllowRowSummaries = AllowRowSummaries.False;

                foreach (UltraGridColumn col in this.DisplayLayout.Bands[0].Columns)
                {
                    if (col.DataType.Equals(typeof(double)))
                    {
                        SummarySettings ss = ssc.Add(SummaryType.Sum, col);
                        ss.Appearance.TextHAlign = Infragistics.Win.HAlign.Right;

                        if (col.Format.Equals("c2", StringComparison.OrdinalIgnoreCase))
                            ss.DisplayFormat = "{0:##,##0.00#} €";
                    }
                }
            }

            if (this.DisplayLayout.Override.AllowRowSummaries == AllowRowSummaries.False)
            {
                this.DisplayLayout.Override.AllowRowSummaries = AllowRowSummaries.True;
                this.DisplayLayout.Override.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;
            }
            else
            {
                this.DisplayLayout.Override.AllowRowSummaries = AllowRowSummaries.False;
                this.DisplayLayout.Override.SummaryDisplayArea = SummaryDisplayAreas.None;
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuPropertyEdit_Click(object sender, EventArgs e)
        {
            OnPropertyEditClick();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuParentPostenPropertyEdit_Click(object sender, EventArgs e)
        {
            int parentId = ((ToolStripMenuItem)sender).Tag.ToInt();

            DataRow[] parentRows = DAO.GetRows(typeof(Posten), "{0}={1}", Posten.Fields.Id, parentId);

            if (!parentRows.Length.Equals(0))
            {
                EditElementProperty(parentRows[0]);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuParentOpponentPropertyEdit_Click(object sender, EventArgs e)
        {
            int parentId = ((ToolStripMenuItem)sender).Tag.ToInt();

            DataRow[] parentRows = DAO.GetRows(typeof(Opponent), "{0}={1}", Opponent.Fields.Id, parentId);

            if (!parentRows.Length.Equals(0))
            {
                EditElementProperty(parentRows[0]);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        protected virtual void OnPropertyEditClick()
        {
            EditElementProperty();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuPropertyNew_Click(object sender, EventArgs e)
        {
            OnPropertyNewClick();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public virtual FrmProperty OnPropertyNewClick()
        {
            ElementBase elementObj = ElementBase.Instantiate(_elementType);
            elementObj.ParentElement = this.ParentElement != null ? this.ParentElement : ((this.Selected.Rows.Count > 0) ? ElementBase.Instantiate(this.Selected.Rows[0].ToDataRow()) : null);

            return EditElementProperty(elementObj.New().Row);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuPropertyCopy_Click(object sender, EventArgs e)
        {
            foreach (UltraGridRow row in Selected.Rows)
            {
                DataRow newrow = row.ToDataRow().Clone();

                if (newrow[Posten.Fields.Label].ToString().Equals("Vorlage"))
                {
                    newrow[Posten.Fields.Label] = "";
                }

                if (newrow.Table.TableName.Equals(typeof(Posten).Name) && newrow.Table.Columns.Contains(Posten.Fields.SerieId))
                {
                    newrow[Posten.Fields.SerieId] = 0;
                }

                if (newrow.Table.TableName.Equals(typeof(Date).Name))
                {
                    newrow[Date.Fields.IsFree] = true;
                    newrow[Date.Fields.Termin] = null;
                }

                EditElementProperty(newrow);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuPropertyDelete_Click(object sender, EventArgs e)
        {
            OnPropertyDeleteClick();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuCopyOverviewToClipboard_Click(object sender, EventArgs e)
        {
            CopyOverviewToClipboard(SelectedRows);
        }

        /// <summary>
        /// 
        /// </summary>
        protected virtual void OnPropertyDeleteClick()
        {
            if (MessageBox.Show("Markierte Einträge inkl. Unterobjekte löschen?", "Einträge löschen", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                DeleteRows(SelectedRows);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuManageColumn_Click(object sender, EventArgs e)
        {
            ColumnChooserDialog dlg = new ColumnChooserDialog();

            UltraGridColumnChooser cc = dlg.ColumnChooserControl;
            cc.SourceGrid = this;
            cc.CurrentBand = this.DisplayLayout.Bands[0];
            cc.ColumnDisplayOrder = ColumnDisplayOrder.SameAsGrid;
            cc.Style = ColumnChooserStyle.AllColumnsWithCheckBoxes;
            cc.MultipleBandSupport = MultipleBandSupport.SingleBandOnly;

            dlg.Size = new System.Drawing.Size(350, 400);
            dlg.Text = "Spalten ein-/ausblenden";
            dlg.Show();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmnuGroupBoxShow_Click(object sender, EventArgs e)
        {
            this.DisplayLayout.GroupByBox.Hidden = !this.DisplayLayout.GroupByBox.Hidden;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void layoutItem_MouseUp(object sender, MouseEventArgs e)
        {
            ToolStripMenuItem layoutItem = (ToolStripMenuItem)sender;
            Type layoutElement = (Type)layoutItem.OwnerItem.Tag;
            string layoutName = ((ToolStripMenuItem)sender).Tag.ToString();

            this.LoadLayout(layoutName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="rows"></param>
        public void DeleteRows(List<UltraGridRow> rows)
        {
            this.Enabled = false;
            Application.DoEvents();

            for (int i = 0; i < rows.Count; i++)
            {
                OnElementDeletingApply(new HEventArgs("Element löschen...", i, rows.Count));

                ElementBase elementObj = ElementBase.Instantiate(rows[i].ToDataRow());
                elementObj.Delete();
            }

            Application.DoEvents();

            OnElementDeletedApply(new HEventArgs(LO.Status("Ready")));

            WindowController.RefreshMonthbalanceGrids();

            this.Enabled = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="rows"></param>
        public void CopyOverviewToClipboard(List<UltraGridRow> rows)
        {
            if (!rows.Count.Equals(0))
            {
                this.Enabled = false;
                Application.DoEvents();

                string contenttitle = string.Join(((char)9).ToString(), rows[0].Cells.Cast<UltraGridCell>().Where(cell => !cell.Column.Hidden).Select(cell => cell.Column.Header.Caption).ToArray());

                string content = string.Join(Environment.NewLine,
                    rows.Select(row => string.Join(((Char)9).ToString(),
                        row.Cells.Cast<UltraGridCell>().Where(cell => !cell.Column.Hidden).
                        Select(cell =>
                            cell.Text.Replace(((Char)9).ToString(), "[Tab]").
                            Replace(Environment.NewLine, ";; ").
                            Replace(" €", "").
                            Replace("\r", ";; ").
                            Replace("\n", ";; ")
                           ).ToArray())));

                Clipboard.SetText(contenttitle + Environment.NewLine + content);

                this.Enabled = true;
            }
        }

        #endregion contextmenu

        #region LAYOUT SUPPORT METHODS

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveDefaultLayout_Click(object sender, EventArgs e)
        {
            SaveLayout(_defaultColumnSet.ToString());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveCurrentLayout_Click(object sender, EventArgs e)
        {
            SaveLayout(CurrentLayoutName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CreateLayout_Click(object sender, EventArgs e)
        {
            SaveLayout("");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteLayout_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Layout löschen?", "Layout löschen", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                if (this.DeleteLayout(CurrentLayoutName))
                {
                    //if (_elementType == FinDate.ElementType)
                    //{
                    //    WindowController.UpdateBankingMenu();
                    //}
                    //else
                    //{
                    WindowController.UpdateElementLayoutMenu(_elementType);
                    //}
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="layoutName"></param>
        protected void SaveLayout(string layoutName)
        {
            GridLayout existsGridLayout = GridLayout.FindLayout(layoutName, _elementType);

            string newLayoutName = layoutName;
            string icon = "";
            bool isStartFavorit = false;

            DialogResult dialogResult = (layoutName != _defaultColumnSet.ToString()) ? DialogResult.Cancel : DialogResult.OK;

            if (layoutName != _defaultColumnSet.ToString())
            {
                FrmLayoutName frmLayoutName = new FrmLayoutName(_elementType, layoutName, existsGridLayout);

                dialogResult = frmLayoutName.ShowDialog();

                newLayoutName = frmLayoutName.LayoutName;
                icon = DAO.HFile.ProvideIcon(frmLayoutName.LayoutIcon);
                isStartFavorit = frmLayoutName.IsStartFavorit;
            }

            if (dialogResult == DialogResult.OK)
            {
                if (this.SaveCurrentLayout(layoutName, newLayoutName, icon, isStartFavorit))
                {
                    //if (_elementType == FinDate.ElementType)
                    //{
                    //    WindowController.UpdateBankingMenu();
                    //}
                    //else
                    //{
                    WindowController.UpdateElementLayoutMenu(_elementType);
                    //}
                }

                LoadLayout(newLayoutName);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="currentLayoutName"></param>
        /// <param name="newLayoutName"></param>
        /// <param name="icon"></param>
        /// <param name="isStartFavorit"></param>
        /// <returns></returns>
        public bool SaveCurrentLayout(string currentLayoutName, string newLayoutName, string icon, bool isStartFavorit)
        {
            DataTable tbl = DAO.Tables[GridLayout.ElementType];

            MemoryStream streamColumnFilters = new MemoryStream();
            this.DisplayLayout.Save(streamColumnFilters, PropertyCategories.ColumnFilters);
            MemoryStream streamSortedColumns = new MemoryStream();
            this.DisplayLayout.Save(streamSortedColumns, PropertyCategories.SortedColumns);

            if (currentLayoutName.Equals(string.Empty))
            {
                DataRow row = tbl.NewRow();
                row[GridLayout.Fields.Name] = newLayoutName;
                row[GridLayout.Fields.Table] = _elementType.Name;
                row[GridLayout.Fields.Icon] = icon;
                row[GridLayout.Fields.StartFavorite] = isStartFavorit;
                row[GridLayout.Fields.ColumnFilters] = Compress.Zip(streamColumnFilters.ToArray());
                row[GridLayout.Fields.SortedColumns] = Compress.Zip(streamSortedColumns.ToArray());
                tbl.Rows.Add(row);
            }
            else
            {
                DataRow[] rows = DAO.GetRows(GridLayout.ElementType, "{0} = '{1}' and {2} = '{3}'", GridLayout.Fields.Table, _elementType.Name, GridLayout.Fields.Name, currentLayoutName);
                if (!rows.Length.Equals(0))
                {
                    rows[0][GridLayout.Fields.Name] = newLayoutName;
                    rows[0][GridLayout.Fields.Icon] = icon;
                    rows[0][GridLayout.Fields.StartFavorite] = isStartFavorit;
                    rows[0][GridLayout.Fields.ColumnFilters] = Compress.Zip(streamColumnFilters.ToArray());
                    rows[0][GridLayout.Fields.SortedColumns] = Compress.Zip(streamSortedColumns.ToArray());
                }
                else
                {
                    DataRow row = tbl.NewRow();
                    row[GridLayout.Fields.Name] = newLayoutName;
                    row[GridLayout.Fields.Table] = _elementType.Name;
                    row[GridLayout.Fields.Icon] = icon;
                    row[GridLayout.Fields.StartFavorite] = isStartFavorit;
                    row[GridLayout.Fields.ColumnFilters] = Compress.Zip(streamColumnFilters.ToArray());
                    row[GridLayout.Fields.SortedColumns] = Compress.Zip(streamSortedColumns.ToArray());
                    tbl.Rows.Add(row);

                    //return false;
                }
            }

            DAO.SaveGridLayout();

            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="layoutName"></param>
        /// <returns></returns>
        public bool DeleteLayout(string layoutName)
        {
            DataTable tbl = DAO.Tables[GridLayout.ElementType];

            DataRow[] rows = DAO.GetRows(GridLayout.ElementType, "{0} = '{1}' and {2} = '{3}'", GridLayout.Fields.Table, _elementType.Name, GridLayout.Fields.Name, layoutName);
            if (rows.Length > 0)
            {
                foreach (DataRow row in rows)
                {
                    tbl.Rows.Remove(row);
                }

                DAO.SaveGridLayout();

                CurrentLayoutName = _defaultColumnSet.ToString();

                return true;
            }
            else
            {
                CurrentLayoutName = _defaultColumnSet.ToString();

                return false;
            }
        }

        /// <summary>
        /// Load default layout
        /// </summary>
        public void LoadLayout()
        {
            _defaultLayout.Position = 0;
            this.DisplayLayout.Load(_defaultLayout);

            CurrentLayoutName = _defaultColumnSet.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="elementType"></param>
        /// <param name="layoutName"></param>
        public void LoadLayout(string layoutName)
        {
            GridLayout gridLayout = GridLayout.FindLayout(layoutName, _elementType);

            if (gridLayout != null)
            {
                //DataRow[] rows = DAO.Tables[GridLayout.ElementType].Select(string.Format("{0} = '{1}' and {2} = '{3}'", GridLayout.Fields.Name, layoutName, GridLayout.Fields.Table, _elementType.Name));
                //if (rows.Length > 0)
                //{
                byte[] columnFilters = Compress.UnzipToArray(gridLayout.ColumnFilters);
                MemoryStream byteStream = new MemoryStream(columnFilters);
                this.DisplayLayout.Load(byteStream, PropertyCategories.ColumnFilters);

                CalculateUnboundFields();

                byte[] sortedColumns = Compress.UnzipToArray(gridLayout.SortedColumns);
                byteStream = new MemoryStream(sortedColumns);

                this.DisplayLayout.Load(byteStream, PropertyCategories.SortedColumns);

                CurrentLayoutName = layoutName;
            }
            else
            {
                LoadLayout();
                CalculateUnboundFields();
            }

            //UpdateLayout();

            base.DisplayLayout.AutoFitStyle = AutoFitStyle.ExtendLastColumn;

            InitializeRowsAppearances();

            if (OnStatusMessage != null)
                OnStatusMessage(typeof(DAO), new HEventArgs(LO.Status("Ready")));
        }

        /// <summary>
        /// 
        /// </summary>
        private void UpdateLayout()
        {
            //if (Program.StartArgs[Program.STARTARG_UPDATELAYOUT].ToBool())
            {
                UltraGridBand band = this.DisplayLayout.Bands[0];
                Dictionary<string, FilterConditionsCollection> filterKeys = new Dictionary<string, FilterConditionsCollection>();
                foreach (ColumnFilter colFilter in band.ColumnFilters)
                {
                    filterKeys.Add(colFilter.Column.Key, colFilter.FilterConditions);
                }

                LoadLayout();

                foreach (ColumnFilter colFilter in band.ColumnFilters)
                {
                    colFilter.FilterConditions.Clear();
                    if (filterKeys.ContainsKey(colFilter.Column.Key))
                    {
                        foreach (FilterCondition fc in filterKeys[colFilter.Column.Key])
                            colFilter.FilterConditions.Add(fc);
                    }
                }
            }
        }

        #endregion LAYOUT SUPPORT METHODS


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HGrid_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point mousePoint = new Point(e.X, e.Y);
                UIElement element = ((UltraGrid)sender).DisplayLayout.UIElement.ElementFromPoint(mousePoint);

                UltraGridCell cell = element.GetContext(typeof(UltraGridCell)) as UltraGridCell;
                if (cell != null)
                {
                    _clickedObject = cell;

                    if (this.Selected.Rows.Count < 2)
                    {
                        this.ActiveRow = null;
                        this.Selected.Rows.Clear();
                        cell.Row.Selected = true;
                    }
                }
                else
                {
                    UltraGridColumn column = element.GetContext(typeof(UltraGridColumn)) as UltraGridColumn;
                    if (column != null)
                    {
                        _clickedObject = column;
                    }
                    else
                    {
                        UltraGrid grid = element.GetContext(typeof(UltraGrid)) as UltraGrid;
                        if (grid != null)
                        {
                            _clickedObject = grid;
                        }
                    }
                }
            }
        }
    }
}
